package com.example.xmpic.ui.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import androidx.annotation.Nullable;
import android.util.Log;

import com.basic.G;
import com.example.xmpic.support.FunPath;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.support.OnFunDeviceFileListener;
import com.example.xmpic.support.OnFunDeviceOptListener;
import com.example.xmpic.support.OnFunDeviceRecordListener;
import com.example.xmpic.support.models.FunDevRecordFile;
import com.example.xmpic.support.models.FunDevice;
import com.example.xmpic.support.models.FunFileData;
import com.example.xmpic.ui.data.CameraLocalFile;
import com.example.xmpic.ui.utils.LocalFileManager;
import com.lib.sdk.struct.H264_DVR_FILE_DATA;

import java.io.File;
import java.util.List;

/**
 * @author skygge
 * @date 2020/7/21.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class DownloadService extends Service implements OnFunDeviceFileListener, OnFunDeviceRecordListener, OnFunDeviceOptListener {
    private static final String TAG = DownloadService.class.getSimpleName();
    private onServiceCallBack mCallBack;
    private FunDevice mFunDevice = null;
    private List<FunFileData> mDownloadFiles;
    private List<CameraLocalFile> mLocalFile;
    private int mCurrentDownTask = 0;
    private int mDownloadSize;

    private DownloadBinder mBinder = new DownloadBinder();

    public class DownloadBinder extends Binder{

        public void setRequestCallBack(onServiceCallBack callBack) {
            mCallBack = callBack;
        }

        public void setDownloadFile(FunDevice funDevice, List<FunFileData> downloadFiles, int size){
            mFunDevice = funDevice;
            mDownloadFiles = downloadFiles;
            mDownloadSize = size;
        }

        public void setLocalFile(List<CameraLocalFile> localFiles){
            mLocalFile = localFiles;
        }

        public void startToDownload(){
            Log.i(TAG, "startToDownload: 开始下载");
            mHandler.sendEmptyMessage(0);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 1. 注册录像文件搜索结果监听 - 在搜索完成后以回调的方式返回
        FunSupport.getInstance().registerOnFunDeviceRecordListener(this);
        FunSupport.getInstance().registerOnFunDeviceOptListener(this);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private Handler mHandler = new Handler(msg -> {
        Log.i(TAG, "sendMessage: " + mCurrentDownTask);
        if (mCurrentDownTask <= mDownloadSize -1){
            startDownload(mCurrentDownTask);
        }else {
            if (mCallBack!=null) {
                mCallBack.onDeviceFileFinish();
            }
            mCallBack = null;
            removeMessage();
        }
        return false;
    });

    /**
     * 下载视频录像
     */
    private void startDownload(int position){
        FunFileData recordFile = mDownloadFiles.get(position);
        if (recordFile != null) {
            String videoName = recordFile.getBeginDateStr() + "_" + recordFile.getBeginTimeStr() + "-" + recordFile.getEndTimeStr() + ".mp4";
            String path = FunPath.PATH_VIDEO + File.separator + mFunDevice.getDevSn() + File.separator + videoName;
            File file = new File(path);
            if (file.exists()) {
                sendMessage(position);
                return;
            }
            byte[] data = G.ObjToBytes(recordFile.getFileData());
            int newPosition = getNewTaskPosition(recordFile);
            FunSupport.getInstance().requestDeviceDownloadByFile(mFunDevice, data, path, newPosition);
            Log.i(TAG, "startToDownload: 创建下载任务");
        }else {
            sendMessage(position);
        }
    }

    private void sendMessage(int position){
        mCurrentDownTask = position +1;
        mHandler.sendEmptyMessage(0);
    }

    private void removeMessage(){
        mHandler.removeMessages(0);
    }

    private int getNewTaskPosition(FunFileData fun){
        String time = fun.getBeginDateStr() + " " + fun.getBeginTimeStr();
        String downTime = LocalFileManager.getInstance().getTimeStamp(time);
        for (int i = 0; i < mLocalFile.size(); i++) {
            String downTime2 = mLocalFile.get(i).getDownTime();
            if (downTime2.equals(downTime)){
                return i;
            }
        }
        return 0;
    }

    @Override
    public void onDeviceFileDownCompleted(FunDevice funDevice, String path, int nSeq) {
        sendMessage(mCurrentDownTask);
        if (mCallBack!=null) mCallBack.onDeviceFileDownCompleted(funDevice, path, nSeq);
    }

    @Override
    public void onDeviceFileDownProgress(int totalSize, int progress, int nSeq) {
        if (mCallBack!=null) mCallBack.onDeviceFileDownProgress(totalSize, progress, nSeq);
    }

    @Override
    public void onDeviceFileDownStart(boolean isStartSuccess, int nSeq) {
        if (mCallBack!=null) mCallBack.onDeviceFileDownStart(isStartSuccess, nSeq);
    }

    @Override
    public void onDeviceLoginSuccess(FunDevice funDevice) {

    }

    @Override
    public void onDeviceLoginFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceGetConfigSuccess(FunDevice funDevice, String configName, int nSeq) {

    }

    @Override
    public void onDeviceGetConfigFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceSetConfigSuccess(FunDevice funDevice, String configName) {

    }

    @Override
    public void onDeviceSetConfigFailed(FunDevice funDevice, String configName, Integer errCode) {

    }

    @Override
    public void onDeviceChangeInfoSuccess(FunDevice funDevice) {

    }

    @Override
    public void onDeviceChangeInfoFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceOptionSuccess(FunDevice funDevice, String option) {

    }

    @Override
    public void onDeviceOptionFailed(FunDevice funDevice, String option, Integer errCode) {

    }

    @Override
    public void onDeviceFileListChanged(FunDevice funDevice) {

    }

    @Override
    public void onDeviceFileListChanged(FunDevice funDevice, H264_DVR_FILE_DATA[] datas) {

    }

    @Override
    public void onDeviceFileListGetFailed(FunDevice funDevice) {

    }

    @Override
    public void onRequestRecordListSuccess(List<FunDevRecordFile> files) {

    }

    @Override
    public void onRequestRecordListFailed(Integer errCode) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //注销录像文件搜索结果监听
        FunSupport.getInstance().removeOnFunDeviceRecordListener(this);
        FunSupport.getInstance().removeOnFunDeviceOptListener(this);
    }
}
